package cn.wzptsoft.mall.service.Impl;

import cn.wzptsoft.mall.mapper.UserMapper;
import cn.wzptsoft.mall.pojo.LoginUser;
import cn.wzptsoft.mall.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);
        //没有查到就抛出异常
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException(username);
        }
        LoginUser loginUser = new LoginUser(user);
        List<String> authorities=null;
//        if (user.getId()==1){
//            authorities=new ArrayList<>();
//            authorities.add("admin");
//            loginUser = new LoginUser(user,authorities);
//        }
        if (user.getUsername().startsWith("admin")){
            authorities=new ArrayList<>();
            authorities.add("ROLE_"+"admin");
            loginUser = new LoginUser(user,authorities);

        }

        return loginUser;
    }

}
